package com.apes.project.jekunAuto.timeTask.scm;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.project.jekunAuto.timeTask.BaseService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.masterdata.area.service.AreaService;
import com.apes.scm.masterdata.area.service.CountryService;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.enumeration.service.EnumerationService;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyIdentification;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyIdentificationRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.party.service.PartyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * Creator: zouyc
 * CreateDate: 2019-12-09 15:40
 * Description:
 **/
@Service("baseInfoSynService")
public class BaseInfoSynService extends BaseService {

    @Autowired
    ContrastPartyCodeRepository contrastPartyCodeRepository;
    @Autowired
    PartyIdentificationRepository partyIdentificationRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    PartyService partyService;
    @Autowired
    AreaService areaService;
    @Autowired
    CountryService countryService;
    @Autowired
    EnumerationService enumerationService;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    TaxService taxService;

    /**
     * party相关信息同步Base
     * supplier custom company
     * @param
     */
    public void synPartyBase(JSONObject simpleObj){
        String thisType = simpleObj.getString("thisType");
        String thisName = simpleObj.getString("name");

        String orginCustomID = simpleObj.getString("customerID");
        String orginSupplierID = simpleObj.getString("supplierID");
        String orginCompanyID = simpleObj.getString("companyID");
        String uscc = simpleObj.getString("uscc");

        String newCustomID = replaceKHIDRule(orginCustomID);
//        String newSupplierID = orginSupplierID;
        String newSupplierID = replaceGysidRule(orginSupplierID);
        String newCompanyID = orginCompanyID;

        String thisID ;
        String origin ;

        switch (thisType){
            case "Company":
                thisID = newCompanyID;
                origin = orginCompanyID;
                break;
            case "Supplier":
                thisID = newSupplierID;
                origin = orginSupplierID;
                break;
            case "Customer":
                thisID = newCustomID;
                origin = orginCustomID;
                break;
                default:
                    throw new RuntimeException("老框架数据有误");

        }
        String thisRowID;

        Party party ;
        ContrastPartyCode contrastPartyCode = new ContrastPartyCode();
        if(contrastPartyCode.getParty() == null && newCustomID != null){
            contrastPartyCode = contrastPartyCodeRepository.findFirstByKhid(orginCustomID);
            if(contrastPartyCode == null) contrastPartyCode = new ContrastPartyCode();
        }
        if(contrastPartyCode.getParty() == null && newSupplierID != null){
            contrastPartyCode = contrastPartyCodeRepository.findFirstByGysid(orginSupplierID);
            if(contrastPartyCode == null) contrastPartyCode = new ContrastPartyCode();
        }
        if(contrastPartyCode.getParty() == null && newCompanyID != null){
            contrastPartyCode = contrastPartyCodeRepository.findFirstByGsid(newCompanyID);
            if(contrastPartyCode == null) contrastPartyCode = new ContrastPartyCode();
        }
        party = contrastPartyCode.getParty();
        if(party == null){
//            PartyIdentification partyIdentification = new PartyIdentification();
//            if(uscc!=null) partyIdentification = partyIdentificationRepository.findFirstByPartyIdTypeAndIdValue("PIT_USCC",uscc);
//            if(partyIdentification != null && partyIdentification.getParty() != null) party = partyIdentification.getParty();

            PartyRole partyRole;
            if(party == null && newCustomID !=null){
                partyRole = partyRoleRepository.findOne(newCustomID);
                if(partyRole != null) party = partyRole.getParty();
            }

            if(party == null && newSupplierID !=null){
                partyRole = partyRoleRepository.findOne(newSupplierID);

                if(partyRole != null) party = partyRole.getParty();
            }

            if(party == null && newCompanyID !=null){
                partyRole = partyRoleRepository.findOne(newCompanyID);
                if(partyRole != null) party = partyRole.getParty();
            }
        }

        if(party == null) party = new Party();

        party = MapUtil.getO(MapUtil.mapped(party),Party.class);

        //设置party基础信息
        String abbreviation = simpleObj.getString("abbreviation");
        String bank = simpleObj.getString("bank");
        String bankAccount = simpleObj.getString("bankAccount");
        String invoiceTitle = simpleObj.getString("invoiceTitle");
        String invoicePhone = simpleObj.getString("invoicePhone");
        String invoiceAddress = simpleObj.getString("invoiceAddress");

        party.setPartyType("corporate");
        if(abbreviation!=null) party.setAbbreviation(abbreviation);
        if(bank != null) party.setBank(bank);
        if(bankAccount!=null) party.setBankAccount(bankAccount);
        if(invoiceTitle!=null) party.setInvoiceTitle(invoiceTitle);
        if(invoicePhone!=null) party.setInvoicePhone(invoicePhone);
        if(invoiceAddress!=null) party.setInvoiceAddress(invoiceAddress);
        if(origin!=null) party.setOrigin(origin);
        if(thisName!= null) party.setName(thisName);

        //设置corporation信息
        Corporate corporate = party.getCorporate() == null ? new Corporate() : party.getCorporate();
        party.setCorporate(corporate);
        setCorporate(simpleObj,corporate); //设置corporate相关信息
        //设置partyRole
        String code = partyService.findRoleCodeByRole(party,thisType); //如果是某一类型同步，只添加该类型的role
        if (code == null) {
            code = thisID;
            party.addPartyRole(thisType,code);
        }
        //设置partyIdetify
        if(party.getPartyIdentifications() != null){
            Set<PartyIdentification> partyIdentifications = new HashSet<>(party.getPartyIdentifications());
            party.setPartyIdentifications(partyIdentifications);
        }

        party =  partyService.saveAndFlush(party, thisType, thisID);

        contrastPartyCode = contrastPartyCodeRepository.findFirstByParty(party);
        if(contrastPartyCode == null) contrastPartyCode = new ContrastPartyCode();
        contrastPartyCode.setParty(party);
        if(newSupplierID != null) contrastPartyCode.setGysid(orginSupplierID);
        if(newCustomID != null) contrastPartyCode.setKhid(orginCustomID);
        if(newCompanyID != null) contrastPartyCode.setGsid(newCompanyID);
        if(contrastPartyCode.getVipid() != null && contrastPartyCode.getKhid()!=null) throw new RuntimeException("custom只能指向一个类型，请手动处理");
        contrastPartyCodeRepository.saveAndFlush(contrastPartyCode);

    }

    private String replaceGysidRule(String orginSupplierID) {
        String newCustomId = orginSupplierID;
        if(orginSupplierID != null){
            int tempLength = 6;
            int idLength = orginSupplierID.length();
            if( !orginSupplierID.matches(".*[a-zA-Z].*") && idLength>=8){
                newCustomId = orginSupplierID.substring(idLength - tempLength);
            }
        }
        return newCustomId;
    }

    /**
     * 新老框架同步客户编码规则
     * 1.如果纯8位流水码，则开头字母换C
     * 2.含英文，则不变
     * @param oldCustomId
     * @return
     */
    private String replaceKHIDRule(String oldCustomId){
        String newCustomId = oldCustomId;
        if(oldCustomId != null && !oldCustomId.matches(".*[a-zA-Z].*")){
            newCustomId = oldCustomId.replaceFirst(".","C");
        }
        return newCustomId;
    }

    /**
     * corporate相关信息
     * @param simpleRequestObj
     */
    private void setCorporate(JSONObject simpleRequestObj,Corporate corporate) {
        String tax = simpleRequestObj.getString("tax");
        Optional<Tax> optionalTax = SpringManager.getBean(TaxRepository.class).findOne(JpaDsl.toCriteriaByEq("origin", tax));
        if (optionalTax.isPresent()) {
            corporate.setTax(optionalTax.get());
        }
        //注册信息
        String regCountry = simpleRequestObj.getString("regCountry");
        String regProvince = simpleRequestObj.getString("regProvince");
        String regCity = simpleRequestObj.getString("regCity");
        String regCounty = simpleRequestObj.getString("regCounty");
        String regAddress = simpleRequestObj.getString("regAddress");
        Double registeredCapital = simpleRequestObj.getDouble("registeredCapital");
        String uscc = simpleRequestObj.getString("uscc");


        Double maxInvoiceValue = simpleRequestObj.getDouble("maxInvoiceValue");
        if(maxInvoiceValue == null) maxInvoiceValue = 0.0;
        String supplierLevel = simpleRequestObj.getString("supplierLevel");
        Boolean insuranceProvider = simpleRequestObj.getBoolean("insuranceProvider");

        corporate.setMaxInvoiceValue(maxInvoiceValue);
        if(supplierLevel != null) corporate.setSupplierLevel(enumerationService.findByDescriAnaTypeOrCreate(supplierLevel,"supplierLevel"));
        if (insuranceProvider != null)corporate.setInsuranceProvider(insuranceProvider);

        if(regCountry!=null) corporate.setRegCountry(countryService.findByPrefix("ID",regCountry));
        if(regProvince!=null) corporate.setRegProvince(areaService.findByStyleCode(regProvince));
        if(regCity!=null) corporate.setRegCity(areaService.findByStyleCode(regCity));
        if(regCounty!=null) corporate.setRegCounty(areaService.findByStyleCode(regCounty));
        if(regAddress!=null) corporate.setRegAddress(regAddress);
        if(registeredCapital!=null) corporate.setRegisteredCapital(registeredCapital);
        if(uscc!=null) corporate.setUscc(uscc);

        //基本信息
        String officeCountry = simpleRequestObj.getString("officeCountry");
        String officeProvince = simpleRequestObj.getString("officeProvince");
        String officeCity = simpleRequestObj.getString("officeCity");
        String officeCounty = simpleRequestObj.getString("officeCounty");
        String officeAddress = simpleRequestObj.getString("officeAddress");
        String postalCode = simpleRequestObj.getString("postalCode");

        if(officeCountry!=null) corporate.setOfficeCountry(countryService.findByPrefix("ID",officeCountry));
        if(officeProvince!=null)corporate.setOfficeProvince(areaService.findByStyleCode(officeProvince));
        if(officeCity!=null)corporate.setOfficeCity(areaService.findByStyleCode(officeCity));
        if(officeCounty!=null)corporate.setOfficeCounty(areaService.findByStyleCode(officeCounty));
        if(officeAddress!=null)corporate.setOfficeAddress(officeAddress);
        if(postalCode!=null)corporate.setPostalCode(postalCode);


        //客户基本信息
        String customGroupName = simpleRequestObj.getString("customGroupName");
        String customerCategoryName = simpleRequestObj.getString("customerCategoryName");
        String shipment_conditions = simpleRequestObj.getString("shipment_conditions");
        String operation = simpleRequestObj.getString("operation");
        String customerCreditGroupName = simpleRequestObj.getString("customerCreditGroupName");
        String deliveryPlace = simpleRequestObj.getString("deliveryPlace");
        String isWantInvoiceTemp = simpleRequestObj.getString("isWantInvoice");
        boolean isWantInvoice = isWantInvoiceTemp == null ? false : isWantInvoiceTemp.trim().equals("1") ? true :false;
        if(customGroupName != null){
            Enumeration enumerationCustomerGroup = enumerationService.findByDescriAnaTypeOrCreate(customGroupName,"customerGroup");
            corporate.setCustomerGroup(enumerationCustomerGroup);
        }
        if(customerCategoryName != null){
            Enumeration enumerationCustomerCategory = enumerationService.findByDescriAnaTypeOrCreate(customerCategoryName,"customerCategory");
            corporate.setCustomerCategory(enumerationCustomerCategory);
        }
        if(shipment_conditions != null){
            Enumeration enumerationShipmentConditions = enumerationRepository.findByTypeAndValue("汽车运输","shipmentConditions");
            corporate.setShipmentConditions(enumerationShipmentConditions);
        }

        if(operation != null){
            Enumeration enumerationOperation = enumerationService.findByDescriAnaTypeOrCreate(operation,"operation");
            corporate.setOperation(enumerationOperation);
        }

        if(customerCreditGroupName != null){
            Enumeration enumerationCustomerCreditGroupName = enumerationService.findByDescriAnaTypeOrCreate(customerCreditGroupName,"customerCreditGroup");
            corporate.setCustomerCreditGroup(enumerationCustomerCreditGroupName);
        }
        if(deliveryPlace!=null) corporate.setDeliveryPlace(deliveryPlace);

        if(isWantInvoiceTemp!=null)corporate.setWantInvoice(isWantInvoice);
    }
}
